<template>
  <a-form-model
    ref="ruleForm"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <div class="list" style="display: flex">

        <div style="width: 100%;">
          <a-table :columns="forList" :data-source="data" bordered>
            <template v-for="(item,index) of forList" :slot="item.name" slot-scope="text, record">
              <div :key="item.name">
                <a-form-model-item :prop="item.name">
                  <a-tree-select
                    v-if="record.editable && item.tagType === 'tree-select'"
                    v-model="record[item.name]"

                    :value="record[item.name]"
                    style="width: 100%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="treeData"
                    placeholder="请选择部门"
                    tree-default-expand-all
                    @change="e => handleChange(e, record.id, `${item.name}`,e)"
                  >
                  </a-tree-select>
                  <a-input
                    v-else-if="record.editable && item.tagType === 'input'"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :placeholder="item.placeholder ? item.placeholder : '请输入'+item.title"
                    :disabled="item.disabled"
                    :class="item.class"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <a-textarea
                    v-else-if="record.editable && item.tagType === 'textarea'"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :placeholder="item.placeholder ? item.placeholder : '请输入'+item.title"
                    :disabled="item.disabled"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                    :class="item.class"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <j-dict-select-tag
                    v-else-if="record.editable && item.tagType === 'dict-select' && item.dictCode"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :dictCode="item.dictCode"
                    :placeholder="item.placeholder ? item.placeholder : '请选择'+item.title"
                    :disabled="item.disabled"
                    :type="item.type"
                    :class="item.class"
                    style="min-width: 100px"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <j-multi-select-tag
                    v-else-if="record.editable && item.tagType === 'dict-multi-tag' && item.dictCode"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :dictCode="item.dictCode"
                    :placeholder="item.placeholder ? item.placeholder : '请选择'+item.title"
                    :disabled="item.disabled"
                    :type="item.type"
                    :class="item.class"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <j-search-select-tag
                    v-else-if="record.editable && item.tagType === 'dict-select' && item.dictOptions && item.dictOptions.length>0"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :dictOptions="item.dictOptions"
                    :placeholder="item.placeholder ? item.placeholder : '请选择'+item.title"
                    :disabled="item.disabled"
                    :class="item.class"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <a-time-picker
                    v-else-if="record.editable && item.tagType === 'time-picker'"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :valueFormat="item.format? item.format: 'HH:mm:ss'"
                    :format="item.format? item.format: 'HH:mm:ss'"
                    :use12Hours="item.use12Hours || item.use12Hours===false? item.showTime: false"
                    :disabled="item.disabled"
                    :class="item.class"
                    style="width: 100%"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <a-date-picker
                    v-else-if="record.editable && item.tagType === 'date-picker'"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :valueFormat="item.format? item.format: 'YYYY-MM-DD HH:mm:ss'"
                    :format="item.format? item.format: 'YYYY-MM-DD HH:mm:ss'"
                    :show-time="item.showTime || item.showTime===false? item.showTime: { format: 'HH:mm:ss' }"
                    :disabled="item.disabled"
                    :class="item.class"
                    style="width: 100%"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <a-range-picker
                    v-else-if="record.editable && item.tagType === 'range-picker'"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :valueFormat="item.format? item.format: 'YYYY-MM-DD HH:mm:ss'"
                    :format="item.format? item.format: 'YYYY-MM-DD HH:mm:ss'"
                    :show-time="item.showTime || item.showTime===false? item.showTime: { format: 'HH:mm:ss' }"
                    :disabled="item.disabled"
                    :class="item.class"
                    style="width: 100%"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <!--//type有cascader、select，默认为cascader-->
                  <j-area-linkage
                    v-else-if="record.editable && item.tagType === 'area-linkage'"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :disabled="item.disabled"
                    :type="item.type"
                    :class="item.class"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <j-image-upload
                    v-else-if="record.editable && item.tagType === 'upload-image'"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :disabled="item.disabled"
                    :bizPath="item.bizPath"
                    :isMultiple="item.isMultiple"
                    :class="item.class"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <j-upload
                    v-else-if="record.editable && item.tagType === 'upload-file'"
                    v-model="record[item.name]"
                    :value="record[item.name]"
                    :disabled="item.disabled"
                    :bizPath="item.bizPath"
                    :isMultiple="item.isMultiple"
                    :class="item.class"
                    @change="e => handleChange(record[item.name], record.id, `${item.name}`)"
                  />
                  <!--//自定义表单项-->
                  <slot v-else-if="item[item.slost]" :name="'slots-' + item.prop"></slot>
                  <template v-else>
                    {{ text }}
                  </template>
                </a-form-model-item>
              </div>
            </template>



            <template slot="operation" slot-scope="text, record">
              <div class="editable-row-operations">
                    <span v-if="record.editable">
                      <a @click="() => save(record.id,record)">保存</a>
                      <a-popconfirm title="取消保存?" @confirm="() => cancel(record.id)">
                        <a>取消</a>
                      </a-popconfirm>
                    </span>
                <span v-else>
                      <a @click="() => edit(record.id)">编辑</a>
                      <a-popconfirm title="确定要删除所编辑的内容?" @confirm="() => onDelete(record.id)">
                        <a href="javascript:;">删除</a>
                      </a-popconfirm>
                    </span>
              </div>
            </template>
            <template slot="footer">
              <a href="javascript:;" @click="handleAdd"> + 添加</a>
            </template>
          </a-table>
        </div>

    </div>
  </a-form-model>
</template>

<script>
export default {
  name: "formList",
  props:['forList','rules'],
  data() {
    return {
      fileLists: [],
      names: [],
      oldData: [],
      treeData: [],
      data: [],


      editingKey: '',

      fileList: [],
      labelCol: { span: 2 },
      wrapperCol: { span: 6 },
      diqu: {},
      other: '',
      pageFilter: {
        pageNo: 1,
        pageSize: 10
      },

      count: 1,

      passCheck: false,
      pass1: false,
      pass2: false,
      pass3: false,
      li: [],
      bf: [],
      key: '',
      roleName: '',
      item: false,
      type: undefined,
      group: undefined,
      id: undefined,
      xp: undefined,
      nameTitle: [],
      bal:false
    }
  },
  watch:{
    data:{
      deep:true,
      handler() {
        // console.log('子组件数据检测警告')
        this.$emit('dataset',this.data)
      },
    }
  },
  methods: {
    titles(val){
      this.bal = true
    },

    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        console.log(valid)
      })
    },

    showModal() {
      this.visible = true
    },
    inputse(val) {
      let arr = []
      arr.push({
        storageAddress: val.url,
        attribute: val.type,
        type: val.group
      })
      this.fileLists = arr
      console.log(this.fileLists)
    },
    huidaio(val) {
      for (let item of val) {
        item.value = item.title
        if (item.children != []) {
          this.huidaio(item.children)
        }
      }
    },

    handleAdd() {
      let index = 1
      const { count, data } = this
      const newData = {
        id:  this.count,
        key: this.count,
        editable: true,
      }
      this.data = [...data, newData]
      console.log(this.data)
      this.count += 1
      // console.log('count:' + newData.id)
    },
    onDelete(id) {
      const dataSource = [...this.data]
      this.data = dataSource.filter(item => item.id !== id)
    },
    chaxun(val, text) {
      let a = text
      for (let item of val) {
        if (text === item.title) {
          this.key = item.key
        } else if (item.children != []) {
          this.chaxun(item.children, a)
        }
      }
    },
    handleChange(value, id, column, e) {
      console.log(value, id, column,e)
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[column] = value
        this.data = newData
      }
      if (value != undefined) {
        for (let item of this.names) {
          if (value === item.realname) {
            // this.roleName =  item.roleName
            for (let index of this.data) {
              if (item.realname === index.name) {
                index.duties = item.roleName
                index.userId = item.id
              }
            }
          }
        }
      }
      if (e != undefined) {
        this.chaxun(this.bf, e)
        getList({ departId: this.key }).then(res => {
          console.log(res)
          if (res.result.records) {
            this.names = res.result.records
          }
        }).catch(error => {

        })
      }
    },
    edit(id) {
      const newData = [...this.data]
      newData.forEach((item, index) => {
        // console.log(item.id, id)
        if (item.id === id) {
          let oldItem = Object.assign({}, item) // 拷贝出新的对象
          this.oldData[index] = oldItem // 当前对象保存到数组，预备取消操作复原用
          if (item) {
            item.editable = true
            this.data = newData
          }
        }
      })
    },
    save(id,record) {
      this.$refs.ruleForm.validate((valid) => {
        if(valid){
          console.log(id,record)
          let newData = [...this.data]
          // let newCacheData = [...this.cacheData];
          let target = newData.find(item => id === item.id)
          // let targetCache = newCacheData.find(item => key ==== item.key);
          if (target) {
            delete target.editable
            this.data = newData
          }
        }
      })

    },
    cancel(id) {
      this.data.forEach((item, index) => {
        if (item.id === id) {
          item.editable = true
          let target = this.oldData[index]
          if (target !== undefined) {
            this.$set(this.data, index, target)
          } else {
            target = {
              id:  this.count,
              key: this.count,
              editable: true,
            }
            this.$set(this.data, index, target)
          }
        }
      })
    }
  },
}
</script>


<style scoped>
.list {
  display: flex;
  flex-direction: column;
}

/deep/ .list .ant-form-item-control-wrapper {
  width: 100% !important;
}

/deep/ .list .ant-col-2 {
  width: 100px !important;
}
.editable-row-operations a {
  margin-right: 8px;
}
/deep/.ant-table-footer{
  display: flex;
  justify-content: center;
}

</style>